import md5 from "md5";

const base = require("./base.controller");

module.exports = class extends base {

    async _initialize() {
        await super._initialize();
    }


    /**
     * 用户登陆成功返回用户的userId以API访问的Token
     * @returns {Promise<void>}
     * 返回数据格式
     * {
     *   "data": {
     *      "userId": "5a7d428d3d1e0dc66e596e39",
     *      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiNWE3ZDQyOGQzZDFlMGRjNjZlNTk2ZTM5IiwiaWF0IjoxNTE4MTU4NDc3LCJleHAiOjE1MTg3NjMyNzd9.xBBBCEihuOK-_g-pdkz4S8j10zat8ekxqh6lD4tR1oo"
     *   },
     *  "code": 1
     * }
     */
    async login() {
        if (this.isPost()) {
            // const post = JSON.parse(this.post);
            const post = this.post;
            if (!(post.hasOwnProperty('username') &&
                    // post.hasOwnProperty('mobile') &&
                    // post.hasOwnProperty('email') &&
                    post.hasOwnProperty('password'))){
                this.error('信息不完整');
                return;
            }
            const username = post.username;
            const password = md5(post.password);

            let user = await this.model('admin/User').findOne({
                username: username,
                password: password,
                status: 1
            }).exec();

            if (user && user.status) {

                let data = {};

                data.userId = user.id;
                //读取密钥
                const jwtOptions = koahub.configs['middleware']['koahub-jwt'];
                const secret = jwtOptions['secret'];
                const jwt = require('jsonwebtoken');
                //https://www.npmjs.com/package/jsonwebtoken
                // data.token = jwt.sign({
                //     data: user.id,
                //     // 设置 token 过期时间
                //     exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30), // 60 seconds * 60 minutes = 1 hour
                // }, secret);

                data.token = jwt.sign({
                    data: user.id
                }, secret, {expiresIn: jwtOptions['expiresIn'] || '7 days'});

                //授权验证通过之后，API可以通过以下代码获取token的信息
                //const userId = this.ctx.state.user.data;//Auth操作在设置token的时候设置了 userId值

                // // sign with RSA SHA256
                // var cert = fs.readFileSync('private.key');  // get private key
                // var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});


                // koahub.logger.debug(data);
                this.success(data);
            } else {
                this.ctx.throw(401, 'Login Error');
            }

        } else {
            this.ctx.throw(401, 'Login Error');
        }
    }

    /**
     * 用户注册，如果注册成功返回用户的userId以API访问的Token
     * @returns {Promise<void>}
     * 返回数据格式
     * {
     *   "data": {
     *      "userId": "5a7d428d3d1e0dc66e596e39",
     *      "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiNWE3ZDQyOGQzZDFlMGRjNjZlNTk2ZTM5IiwiaWF0IjoxNTE4MTU4NDc3LCJleHAiOjE1MTg3NjMyNzd9.xBBBCEihuOK-_g-pdkz4S8j10zat8ekxqh6lD4tR1oo"
     *   },
     *  "code": 1
     * }
     */
    async register() {
        if (this.isPost()) {
            // const post = JSON.parse(this.post);
            const post = this.post;

            if (!(post.hasOwnProperty('username') &&
                post.hasOwnProperty('mobile') &&
                post.hasOwnProperty('email') &&
                post.hasOwnProperty('password'))){
                this.error('注册信息不完整');
                return;
            }
            // koahub.logger.debug(post.password);
            const mobile = post.mobile;
            const username = post.username;
            const password = md5(post.password);
            const email = post.email;

            const User = this.model('admin/User');

            if (await User.findOne({username: username,}).exec()) {
                //用户已经注册过
                this.error('用户名已经存在');
                return;
            }
            if (await User.findOne({mobile: mobile}).exec()) {
                //手机号码已经注册过
                this.error('手机号码已经注册过');
                return;
            }
            if (await User.findOne({mobile: mobile}).exec()) {
                //手机号码已经注册过
                this.error('手机号码已经注册过');
                return;
            }

            let user = await User.create({
                username: username,
                password: password,
                status: 1,
                mobile: mobile,
                email: email
            });

            if (user && user.status) {

                let data = {};

                data.userId = user.id;
                //读取密钥
                const jwtOptions = koahub.configs['middleware']['koahub-jwt'];
                const secret = jwtOptions['secret'];
                const jwt = require('jsonwebtoken');
                //https://www.npmjs.com/package/jsonwebtoken

                data.token = jwt.sign({
                    data: user.id
                }, secret, {expiresIn: jwtOptions['expiresIn'] || '7 days'});

                //授权验证通过之后，API可以通过以下代码获取token的信息
                //const userId = this.ctx.state.user.data;//Auth操作在设置token的时候设置了 userId值

                koahub.logger.debug(data);
                this.success(data);
            } else {
                this.ctx.throw(401, 'Register Error');
            }

        } else {
            this.ctx.throw(401, 'Register Error');
        }
    }
};
